#include "reader.h"

#include <QThread>
#include <QTime>
#include <QDebug>
#include <QTest>
#include <QObject>

static int randInt(int low, int high)
{
    // Random number between low and high
    return qrand() % ((high + 1) - low) + low;
}

Reader::Reader(Shelf& shelf, int cooldown, QObject* parent)
    : shelf_(shelf)
    , readTime_(cooldown)
    , QObject(parent)
{
    QTime time = QTime::currentTime();
    qsrand((uint)time.msec());
}

void Reader::run()
{
    Qt::HANDLE tid = QThread::currentThreadId();

    while(true) {
        // Reading book
        int bookToRead = randInt(0, shelf_.size() - 1);
        qDebug() << tid << "R want to read " << bookToRead;
        if(!shelf_.takeForReading(bookToRead)) {
            qDebug() << tid << "\t but it's already taken " << bookToRead;
            continue;
        }
        qDebug() << tid << "R took " << bookToRead;

        // Read in progress
        QTest::qSleep(readTime_);

        shelf_.returnBook(bookToRead);
        qDebug() << tid << "R returned " << bookToRead;

        QCoreApplication::processEvents();
    }
}
